package org.fuxia.im.core.socket;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 用于传输文件的客户端
 * 
 * @author Fuxia
 */
public class FileTransferSocketClient implements Runnable
{
	private Socket				client;
	private String				ipAddress	= "localhost";
	private int					port		= 8888;
	private File				file = null ;
	private boolean isCreate;
	private FileTransferCallBack callBack;

	private FileTransferSocketClient()
	{
		this.createClient();
	}

	public FileTransferSocketClient(int port, String address)
	{
		this.port = port;
		this.ipAddress = address;
		this.createClient();
	}

	private void createClient()
	{
		try
		{
			client = new Socket(ipAddress, port);
			setCreate(true);
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public static FileTransferSocketClient newInstance()
	{
		return new FileTransferSocketClient();
	}

	public static FileTransferSocketClient newInstance(int port , String ipAddress)
	{
		return new FileTransferSocketClient(port, ipAddress);
	}

	public void sendFile(File file)
	{
		try
		{
			InputStream fis = new FileInputStream(file);
			long count = 0;
			byte[] buffer = new byte[1024];
			while ((fis.read(buffer)) != -1 && isCreate)
			{
				count += buffer.length;
				client.getOutputStream().write(buffer);
				callBack.callBack(count);
			}
			fis.close();
			if(isCreate) {
				callBack.callBack("end");
			}else{
				callBack.callBack("cancel");
			}
			
		}
		catch (FileNotFoundException e)
		{
			callBack.callBack("error");
		}
		catch (IOException e)
		{
			// non-op
		}finally{
			setCreate(false);
		}

	}

	public boolean isCreate() {
		return isCreate;
	}

	public void setCreate(boolean isCreate) {
		this.isCreate = isCreate;
	}

	public FileTransferCallBack getCallBack() {
		return callBack;
	}

	public void setCallBack(FileTransferCallBack callBack) {
		this.callBack = callBack;
	}

	public void shutdown() {
		try {
			this.client.close();
		} catch (IOException e) {
			// close option
		}
	}

	public void run() {
		sendFile(getFile()) ;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
}
